const Mock = require('mockjs')
const bodyParser = require('body-parser')
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
const data = Mock.mock({
  "list|10": [{
    "id": "@id",
    "title|1": ["前端开发工程师", "高级前端工程师", "web前端工程师", "后端工程师", "前端架构师", "前端地图测试", "UI", "产品经理"],
    "price": "@integer(10,15)-@integer(15,30)K",
    "experience": "@integer(1, 3)-@integer(5,10)",
    "education|1": ["专科", "本科", "研究生", "博士", "博士后"],
    "stack": ["Vue", 'React', "Nodejs"], 
    "name": "@cname",
    "city": "@city",
  }]
})
const userList = [{
  "id": "1231231231231",
  "username": 'zhangsan',
  "password": "zhangsan",
  "nickname": "一直会飞小衫啊",
  "avator": "https://robohash.org/123?set=set5"
},{
  "id": "123124234t45542312312",
  "username": 'lisi',
  "password": "lisi",
  "nickname": "有梦想小四",
  "avator": "https://robohash.org/123123123123123?set=set5"
}]
const OSS = require('ali-oss')

const client = new OSS({
  // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
  region: 'oss-cn-hangzhou',
  // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
  accessKeyId: 'LTAI5tEX1fytQpS8Sgk76uD6',
  accessKeySecret: 'yPDufmJSyiFmsS4H9A0TrMhIbmhLIi',
  // 填写Bucket名称。
  bucket: '2012a-4',
});

module.exports = app => {
  app.use(bodyParser.json())

  app.get('/api/list', (req, res) => {
    res.send({
      code: 200,
      data: data.list
    })
  })

  app.post('/api/login', (req, res) => {
    const { username, password } = req.body;

    const user = userList.find(v => {
      return v.username === username && v.password === password
    })


    if(user) {
      res.send({
        code: 200,
        message: '登录成功',
        data: {
          id: user.id,
          nickname: user.nickname,
          avator: user.avator,
          token: 'daweqweqkwje,nqkmwl;elqkw,;e.klmqwl;elqmweqw'
        }
      })
    } else {
      res.send({
        code: 401,
        message: '登录失败， 请重新登录',
      })
    }
  })

  app.post('/api/upload', multipartMiddleware, async (req, res) => {
    // 获取发送过来的文件
    const { name, path } = req.files.file
    // 上传oss
    const result =  await client.put(name, path)
    res.send({
      code: 200,
      data: result,
      message: 'ok'
    })
  })
}